import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { renderWithQiankun, qiankunWindow, type QiankunProps } from 'vite-plugin-qiankun/dist/helper'
import './style.css'
import App from './App.vue'
import router from './router'

function render(props: QiankunProps = {}) {
  const { container } = props
  const app = createApp(App)
  app.use(createPinia())
  app.use(router)
  container
    ? app.mount(container.querySelector('#app') as HTMLElement)
    : app.mount('#app')
  return app
}

function initApp() {
  if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
    console.log('%c 独立渲染', 'color: red; font-size: 20px;')
    render()
    return
  }
  renderWithQiankun({
    mount(props) {
      console.log('%c qiankun 渲染', 'color: red; font-size: 20px;')
      console.log('主应用传递的props:', props)
      
      // 初始化全局环境对象
      if (!(window as any).__MICRO_APP_ENVIRONMENT__) {
        (window as any).__MICRO_APP_ENVIRONMENT__ = {}
      }
      
      // 保存主应用传递的actions和初始状态
      (window as any).__MICRO_APP_ENVIRONMENT__.globalState = {
        // 保存整个props对象
        ...props,
        // 确保userInfo字段存在
        userInfo: props.userInfo || null,
        // 单独保存actions以便调用
        actions: props.actions
      }
      
      console.log('初始化后的全局状态:', (window as any).__MICRO_APP_ENVIRONMENT__.globalState)
      
      // 如果有actions，立即尝试获取最新的全局状态
      if (props.actions) {
        // 这里可以添加一个回调来监听全局状态变化
        props.actions.onGlobalStateChange((state: any) => {
          console.log('全局状态变化:', state)
          if ((window as any).__MICRO_APP_ENVIRONMENT__) {
            (window as any).__MICRO_APP_ENVIRONMENT__.globalState.userInfo = state.userInfo
          }
        }, true)
      }
      
      render(props)
    },
    bootstrap() {
      console.log('bootstrap')
    },
    unmount(props) {
      console.log('unmount', props)
      // 清理应用实例
      const container = props.container || document
      const appElement = container.querySelector('#app')
      if (appElement) {
        const app = createApp({})
        app.unmount()
      }
    },
    update(props) {
      console.log('update', props)
    },
  })
}

initApp()
